<?php

namespace App\Http\Controllers\Api\V1\Mes;

use App\Constants\BaseConstant;
use App\Constants\Mes\AuthUserConstant;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Controller;
use App\Models\HR\Employee;
use App\Models\Mes\AuthRole;
use App\Models\Mes\AuthUser;
use App\Models\Mes\AuthUserRole;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AuthUserController extends Controller
{
    /*
     * 员工列表
     */
    public function list(Request $request) :JsonResponse
    {
        $employees = Employee::query()
            ->where("EmployeeStateId", "not like", "EmployeeState3%")
            ->when($request, function ($query) use ($request) {
                if ($request->input("name")) {
                    $query->where("CnName", "like", "%" . $request->input("name") . "%");
                }
                if ($request->input("code")) {
                    $query->where("Code", $request->input("code"));
                }
                return $query;
            })
            ->orderBy("CreateDate", "desc")
            ->paginate($request->input("size") ?: 20);
        $list = $employees->getCollection()->map(function ($item) {
            $status = $item->auth_user->status ?? BaseConstant::UNABLE;
            $roles = [];
            if ($item->auth_user) {
                $roles = $item->auth_user->auth_roles->pluck("role_id");
            }
            return [
                "name" => $item->CnName,
                "code" => $item->Code,
                "status" => (string)$status,
                "status_formatted" => BaseConstant::$statuses[$status],
                "roles" => $roles
            ];
        });
        $max_pages = $employees->lastPage();
        $total = $employees->total();
        // 角色列表
        $roles = AuthRole::query()
            ->orderBy("id", "desc")
            ->get()
            ->map(function ($item) {
                return $item->only(["id", "name"]);
            })
        ;
        $return = compact("list", "max_pages", "total", "roles");
        return ResponseHelper::json(0, "success", $return);
    }

    /*
     * 编辑用户信息
     */
    public function modify(Request $request) :JsonResponse
    {
        try {
            $data = $request->all();
            $status = implode(",", array_keys(BaseConstant::$statuses));
            $validator = Validator::make($data, [
                "code" => "required",
                "name" => "required",
                "password" => "nullable",
                "roles" => "nullable|array",
                "status" => "required|in:{$status}"
            ], [
                "code.*" => "用户信息异常",
                "name.*" => "请填写姓名",
                "password.*" => "请填写密码",
                "roles.*" => "请选择角色",
                "status.*" => "请选择用户状态"
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            DB::beginTransaction();
            // 如果用户已经存在
            $auth_user = AuthUser::query()->where("code", $data["code"])->first();
            if ($auth_user) {
                if (isset($data["password"]) && $data["password"]) {
                    $auth_user->password = bcrypt($data["password"]);
                }
                $auth_user->status = $data["status"];
                $auth_user->save();
                // 删除用户角色
                AuthUserRole::query()->where("user_id", $auth_user->id)->delete();
            } else {
                // 用户不存在，新建用户，此时要求密码必填
                if (!(isset($data["password"]) && $data["password"])) {
                    throw new \Exception("请填写密码");
                }
                $auth_user = AuthUser::query()->create([
                    "code" => $data["code"],
                    "name" => $data["name"],
                    "password" => bcrypt($data["password"]),
                    "status" => $data["status"]
                ]);
            }
            if ($data["roles"]) {
                foreach ($data["roles"] as $role) {
                    AuthUserRole::query()->create([
                        "user_id" => $auth_user->id,
                        "role_id" => $role
                    ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "修改成功");
    }

    /*
     * 删除
     */
    public function delete(Request $request) : JsonResponse
    {
        try {
            $data = $request->all();
            DB::beginTransaction();
            $user = AuthUser::query()->where("code", $request->input("code"))->first();
            if (!$user) {
                throw new \Exception("您尚未为该员工创建用户，无需删除");
            }
            AuthUserRole::query()->where("user_id", $user->id)->delete();
            $user->delete();
            DB::commit();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }
}
